<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="sub">
    <BasicForm @register="registerForm">
      <template #pricesSlot="{ model, field }">
        <InputGroup compact>
          <Select v-model:value="currencyType" :options="currencyTypeList" />
          <Input style="width: 50%" @blur="add" v-model:value="model[field]" />
        </InputGroup>
      </template>
      <template #activityTimeSlot="{ model, field }">
        <RangePicker format="YYYY.MM.DD" v-model:value="model[field]" />
      </template>
      <template #activityUrlSlot="{ model, field }">
        <UploadFile :maxNumber="9" @change="model[field]" :api="uploadImgApi" :list="imglist" />
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts">
  import moment from 'moment';
  import { defineComponent, ref, computed, unref, toRefs } from 'vue';
  import { getAppEnvConfig } from '/@/utils/env';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { throttle } from '/@/utils/throttle';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormSchema } from '/@/components/Table';
  import { Select, DatePicker, Input } from 'ant-design-vue';
  import { AddActivityApi, UpdateActivityApi } from '/@/api/merchant/index';
  import { Currency, currencyTypeList } from '/@/utils/currencyType';
  import { UploadApi } from '/@/api/article/index';
  import { convert, outputcents } from '/@/utils/throttle';
  export interface FormState {
    businessId?: string | number;
    id?: string | number;
    activityName: string;
    price: string;
    activityTime: string;
    activityUrl: string;
  }
  export const formSchema: FormSchema[] = [
    {
      label: 'id',
      field: 'businessId',
      component: 'Input',
      show: false,
    },
    {
      label: 'id',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      field: 'activityName',
      label: '活动名称：',
      component: 'Input',
      rules: [
        {
          required: true,
          message: '请输入活动名称',
        },
      ],
      colProps: { span: 22 },
    },
    {
      field: 'price',
      label: '活动价格：',
      component: 'Input',
      slot: 'pricesSlot',
      colProps: { span: 22 },
    },
    {
      field: 'activityTime',
      label: '活动起止时间：',
      component: 'RangePicker',
      slot: 'activityTimeSlot',
      rules: [
        {
          required: true,
          message: '请选择活动起止时间',
        },
      ],
      colProps: { span: 22 },
    },
    {
      field: 'activityUrl',
      label: '商品图片/视频：',
      // component: 'UploadFile',
      component: 'Upload',
      componentProps: {
        api: UploadApi,
        accept: ['jpg', 'jepg', 'png', 'jpeg', 'JPG', 'PNG', 'JEPG', 'Mp4', 'mp4', 'JPEG'],
        maxNumber: 1,
        maxSize: 100,
      },
      // slot: 'activityUrlSlot',
      rules: [
        {
          required: true,
          validator: async (rule, value) => {
            if (!value) {
              /* eslint-disable-next-line */
              return Promise.reject('请上传商品图片/视频');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      colProps: { span: 22 },
    },
  ];

  export default defineComponent({
    name: 'ActivityModal',
    components: {
      BasicModal,
      BasicForm,
      Select,
      RangePicker: DatePicker.RangePicker,
      Input,
      InputGroup: Input.Group,
    },
    props: {
      id: {
        type: String,
        default: '',
      },
    },
    setup(props, { emit }) {
      const { id } = toRefs(props);
      // 图片
      const imglist = ref([]);
      // 图片APi
      const uploadImgApi = ref<string>(getAppEnvConfig().VITE_GLOB_API_URL + '/mini/getFileUrl');
      const isUpdate = ref(true);
      // 货币类型
      const currencyType = ref<string>('$');
      // 时间
      let time = ref<any>('');
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
        fieldMapToTime: [
          // data为时间组件在表单内的字段，startTime，endTime为转化后的开始时间于结束时间
          // 'YYYY-MM-DD'为时间格式，参考moment
          ['activityTime', ['startTime', 'endTime'], 'YYYY.MM.DD'],
          // 支持多个字段
        ],
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        isUpdate.value = !!data?.isUpdate;
        setFieldsValue({ businessId: unref(id) });
        if (unref(isUpdate)) {
          const record = data.record;
          const keys = ['id', 'activityName', 'price', 'activityTime', 'activityUrl'];
          const obj = {};
          currencyType.value = record.symbol || '';
          for (const key of keys) {
            if (key == 'activityTime') {
              const index: Number = record[key].indexOf('-');
              if (index != -1) {
                const timeValue = record[key].split('-');
                obj[key] = [moment(timeValue[0]), moment(timeValue[1])];
              }
            } else if (key == 'price') {
              obj[key] = record[key] ? convert(record[key]) : '';
            } else if (key == 'activityUrl') {
              obj[key] = record[key] ? [record[key]] : [];
            } else {
              obj[key] = record[key];
            }
          }
          setFieldsValue(obj);
        }
      });
      function add(e) {
        const value = e.target.value.replace(/,/g, '');
        setFieldsValue({ price: convert(value) });
      }
      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          const values = await validate();
          values.symbol = unref(currencyType);
          values.activityUrl = values.activityUrl.join(',');
          if (values.price) {
            values.price = Number(values.price.replace(/,/g, ''));
          } else {
            delete values.price;
          }
          values.activityTime = `${moment(values.activityTime[0]).format('YYYY.MM.DD')}-${moment(
            values.activityTime[1]
          ).format('YYYY.MM.DD')}`;
          // values.parentId = 0 | values.parentId;
          if (values.id > 0) {
            await UpdateActivityApi(values);
          } else {
            await AddActivityApi(values);
          }
          closeModal();
          emit('success');
          imglist.value = [];
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      const sub = throttle(handleSubmit);
      function videoChange(record: string[]) {
        setFieldsValue({ activityUrl: record });
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增活动' : '编辑活动'));
      return {
        add,
        moment,
        getTitle,
        registerForm,
        sub,
        registerModal,
        currencyType,
        currencyTypeList,
        imglist,
        uploadImgApi,
        videoChange,
      };
    },
  });
</script>

<style scoped></style>
